/*
 * @lc app=leetcode.cn id=92 lang=golang
 *
 * [92] 反转链表 II
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func reverseBetween(head *ListNode, m int, n int) *ListNode {
	dn := &ListNode{Next: head}
	prev := dn
	for i := 0; i < m-1 && prev.Next != nil; i++ {
		prev = prev.Next
	}

	if prev.Next == nil {
		return nil
	}

	current := prev.Next
	for i := 0; i < m-n; i++ {
		tmp := prev.Next
		prev.Next = current.Next
		current.Next = prev.Next.Next
		prev.Next.Next = tmp
	}

	return dn.Next
}

// @lc code=end

